package fun.tan90.easy.binlog.plugin.redis.sentinel.config;

import com.github.benmanes.caffeine.cache.CacheLoader;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.model.OutputParam;
import fun.tan90.easy.binlog.plugin.redis.common.constants.RedisPluginConstants;
import fun.tan90.easy.binlog.plugin.redis.sentinel.model.RedisSentinelParams;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.noear.dami.Dami;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.time.Duration;
import java.util.Objects;
import java.util.Set;

/**
 * description 动态连接mqtt
 * company 铁人科技
 *
 * @author Li YuLong
 * @date 2023/8/17 10:56
 */
@Slf4j
public class RedisSentinelCacheLoader implements CacheLoader<String, JedisSentinelPool> {

    @Override
    public @Nullable JedisSentinelPool load(@NonNull String outputCode) throws Exception {
        OutputParam outputParam = Dami.<String, OutputParam>bus().sendAndRequest(DamiEventConstants.OUTPUT_PARAM_TOPIC, outputCode);
        if (Objects.isNull(outputParam)) {
            return null;
        }
        RedisSentinelParams redisSentinelParams = (RedisSentinelParams) outputParam;
        // 创建连接池配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(redisSentinelParams.getMinIdle());   // 设置最小空闲连接数
        poolConfig.setMaxIdle(redisSentinelParams.getMaxIdle());   // 设置最大空闲连接数
        poolConfig.setMaxTotal(redisSentinelParams.getMaxTotal()); // 设置最大连接数
        poolConfig.setMaxWait(Duration.ofMillis(redisSentinelParams.getMaxWait()));   // 设置从连接池获取连接的最大等待时间

        String masterName = redisSentinelParams.getMasterName();
        Set<String> sentinels = redisSentinelParams.getSentinels();
        int timeout = redisSentinelParams.getTimeout();
        int soTimeout = RedisPluginConstants.SO_TIMEOUT;
        String user = StringUtils.hasLength(redisSentinelParams.getUser()) ? redisSentinelParams.getUser() : null;
        String password = StringUtils.hasLength(redisSentinelParams.getPassword()) ? redisSentinelParams.getPassword() : null;
        int database = redisSentinelParams.getDatabase();
        return new JedisSentinelPool(masterName, sentinels, poolConfig, timeout, soTimeout, user, password, database, "eb_redis_sentinel");
    }
}